﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.Data.SqlClient;
using System.Runtime.Remoting.Contexts;
using System.Windows.Forms;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;

namespace Systemathics.Installer
{
    [RunInstaller(true)]
    public class SystemathicsInstaller : System.Configuration.Install.Installer
    {
        public SystemathicsInstaller()
        {
            AfterInstall += MyInstallerClassAfterInstall;
        }

        private void MyInstallerClassAfterInstall(object sender, InstallEventArgs e)
        {
            string Path = Context.Parameters["INSTALLDIR"];
            Environment.SetEnvironmentVariable("SYSTEMATHICS", Path, EnvironmentVariableTarget.User);

            Path = "C:\\Program Files\\Microsoft SQL Server\\MSSQL10.SQLEXPRESS2008\\MSSQL\\DATA\\";
            Environment.SetEnvironmentVariable("SYSTEMATHICS_DB", Path, EnvironmentVariableTarget.User);

            var sqlBuilder = new SqlConnectionStringBuilder
                                 {
                                     DataSource = ".\\SQLEXPRESS2008",
                                     InitialCatalog = "master",
                                     IntegratedSecurity = true,
                                     MultipleActiveResultSets = true
                                 };

            Path = Context.Parameters["INSTALLDIR"] + "Resources\\Systemathics.bak";
            RestoreDatabase("SYSTEMATHICS", Path, new SqlConnection(sqlBuilder.ToString()));

            Path = Context.Parameters["INSTALLDIR"] + "Resources\\TickCaptures.bak";
            RestoreDatabase("TICKCAPTURES", Path, new SqlConnection(sqlBuilder.ToString()));
        }

        public override void Uninstall(IDictionary savedState)
        {
            Environment.SetEnvironmentVariable("SYSTEMATHICS", null, EnvironmentVariableTarget.User);
            Environment.SetEnvironmentVariable("SYSTEMATHICS_DB", null, EnvironmentVariableTarget.User);
            base.Uninstall(savedState);
        }

        private static void RestoreDatabase(string databaseName, string backUpFile, SqlConnection conn)
        {
            try
            {
                var connection = new ServerConnection(conn);
                var sqlServer = new Server(connection);
                var rstDatabase = new Restore { Action = RestoreActionType.Database, Database = databaseName };
                var bkpDevice = new BackupDeviceItem(backUpFile, DeviceType.File);
                rstDatabase.Devices.Add(bkpDevice);
                rstDatabase.ReplaceDatabase = true;
                rstDatabase.SqlRestore(sqlServer);
            }
            catch (Exception ex)
            {
                MessageBox.Show(backUpFile);
                MessageBox.Show(ex.Message);
            }
        }
    }
}